#!/bin/bash
#===================================================
# 脚本名称: install_docker.sh
# 版本: 1.0
# 更新日志:
# - 2025-01-22: 初始版本，符合Shell脚本最佳实践
# - 2025-01-23: 添加日志功能和错误处理
#===================================================

set -o errexit    # 遇到错误立即退出
set -o nounset    # 遇到未定义变量报错
set -o pipefail   # 管道命令中任意失败则整体失败
set -o xtrace     # 调试模式显示行号

# 常量定义
readonly CONFIG_FILE="config/docker/daemon.json"

# 获取最新稳定版
get_latest_version() {
    logger -t "$0" "[INFO] 正在获取最新稳定版..."
    local version=$(curl -sSL https://api.github.com/repos/moby/moby/releases/latest | grep '"tag_name":' | sed -E 's/.*"v([^"]+)".*/\1/')
    
    if [[ -z "$version" ]]; then
        logger -t "$0" "[ERROR] 无法获取Docker版本"
        exit 1
    fi
    
    echo "$version"
    logger -t "$0" "[INFO] 最新稳定版: $version"
}
readonly LOG_FILE="/var/log/docker_install.log"

# 初始化日志
init_logger() {
    exec &> >(tee -a "$LOG_FILE")
    logger -t "$0" "=== 开始执行Docker安装脚本 ==="
}

# 清理临时文件
cleanup() {
    local exit_code=$?
    logger -t "$0" "开始清理临时资源，退出码：$exit_code"
    
    if [[ -d "${TEMP_DIR:-}" ]]; then
        rm -rf "$TEMP_DIR"
        logger -t "$0" "已清理临时目录: $TEMP_DIR"
    fi
    
    exit $exit_code
}

# 检查root权限
check_privileges() {
    if [[ $EUID -ne 0 ]]; then
        logger -t "$0" "[ERROR] 需要root权限运行此脚本"
        exit 1
    fi
}

# 安装依赖
install_dependencies() {
    logger -t "$0" "[INFO] 正在安装依赖..."
    apt-get update -qq && apt-get install -y \
        apt-transport-https \
        ca-certificates \
        curl \
        gnupg-agent \
        software-properties-common
}

# 配置docker源
configure_repo() {
    logger -t "$0" "[INFO] 配置Docker官方源..."
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
}

# 应用配置
apply_configuration() {
    logger -t "$0" "[INFO] 应用Docker配置..."
    mkdir -p /etc/docker
    
    # 直接生成daemon.json配置
    cat > /etc/docker/daemon.json <<EOF
{
  "data-root": "/data/docker",
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "3"
  }
}
EOF
    
    # 创建数据目录并设置权限
    mkdir -p /data/docker
    chmod 700 /data/docker
    logger -t "$0" "[INFO] 已生成Docker守护进程配置"
    
    # 验证配置生效
    if ! docker info | grep -q "Docker Root Dir: /data/docker"; then
        logger -t "$0" "[ERROR] 配置未正确应用"
        exit 1
    fi
}

# 主安装流程
main() {
    trap cleanup EXIT INT TERM ERR
    TEMP_DIR=$(mktemp -d)
    
    init_logger
    check_privileges
    install_dependencies
    configure_repo
    
    # 动态获取版本号
    local DOCKER_VERSION=$(get_latest_version)
    
    logger -t "$0" "[INFO] 正在安装Docker $DOCKER_VERSION..."
    apt-get update -qq
    apt-get install -y --allow-downgrades \
        docker-ce=$DOCKER_VERSION \
        docker-ce-cli=$DOCKER_VERSION \
        containerd.io
    
    apply_configuration
    
    systemctl enable --now docker
    docker version
}

main "$@"